/*
 * Copyright (c) 2011 Junichiro Okuno
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are those of the
 * authors and should not be interpreted as representing official policies, either expressed
 * or implied, of Junichiro Okuno.
 */

package tcp_net.mail.smtp.states;

import tcp_net.TextInputOutput;
import tcp_net.mail.MailBoxFileManager;
import tcp_net.mail.smtp.commands.*;
import tcp_net.MessageProcessor;
import tcp_net.mail.EmailMessageProcessor;
import tcp_net.mail.smtp.states.debug.DebugInfo;
import tcp_net.mail.smtp.client.SMTPClient;
import tcp_net.mail.smtp.client.MXLookup;
import java.util.List;
import java.util.ArrayList;

/**
	Data state for SMTP server
	@author J. Okuno
*/
public class Data extends SMTPState
{
	/**
		A file path to a list of local domain names
	*/
	private final static String DOMAIN_LIST = "conf/domain_list.txt";
	
	/**
		Debug information
	*/
	private final static boolean DEBUG = DebugInfo.DATA_DEBUG;
	
	/**
		An email header and a message
	*/
	private String mail_data;
	
	/**
		true mx record conversion is enabled
	*/
	private boolean mx_record_enabled;
	
	/**
		Init Data
		@param mx true mx record conversion is enabled
	*/
	public Data(boolean mx) 
	{
		mx_record_enabled = mx;
		mail_data = "";
		DebugInfo.print(DEBUG, "Data State created");
	}
	
	/**
		Init Data
	*/
	public Data() { this(true); }
	
	/**
		This method process a defined request (a command and its arguments) from a POP3 client
		@param pmp a message processor
		@param str_command a command request in a string text format
		@param arguments a list of arguments in a string text format 
		@return a list of replies
	*/
	public List<String> process(MessageProcessor pmp, String str_command, List<String> arguments)
	{
		String output = str_command;
		for(String arg : arguments) { output += " " + arg; }
		DebugInfo.print(DEBUG, "Data State process() output: "+output);
		
		if(output.equals("."))
		{
			mail_data += output;
		}
		else
		{
			mail_data += output+"\r\n";
		}
		
		if(output.equals("."))
		{
			DebugInfo.print(DEBUG, "Data State process() output is: .");
			
			MailBoxFileManager man = ((EmailMessageProcessor)pmp).getMailBoxFileManager();
			
			for(String email_address : man.getReceptAddresses())
			{
				String domain = man.getDomain(email_address);
				DebugInfo.print(DEBUG, "Domain is: "+domain);
				
				
				boolean local = false;
				
				//Reference from the local domain list
				List<String> domains = TextInputOutput.getTextAsList(DOMAIN_LIST);
				for(String d : domains) 
				{ 
					DebugInfo.print(DEBUG,"Local domain: "+d);
					if(domain.equals(d)) 
					{ 
						DebugInfo.print(DEBUG,"Local domain");
						
						local = true; 
						break;
					}
				}
				
				//Local host
				// Need to record mail data
				if(local)
				{
					DebugInfo.print(DEBUG, "Mail is to be delivered to localhost");
					
					String user = man.getUserName(email_address);
				
					if(man.isUserValid(user))
					{
						DebugInfo.print(DEBUG, "User: "+user+" Mail data: "+mail_data);
						man.deliverMessage(user, mail_data);
					}
					else
					{
						//Clear all recp email addresses
						man.clearReceptAddresses();
			
						//Error (Unable to find a user)
						ArrayList<String> out_list = new ArrayList<String>();
						out_list.add("551 User not local");
						
						DebugInfo.print(DEBUG, "Data State: Replied");
						pmp.changeState(new Transaction());
			
						return out_list;
					}
				}
			
				//Retransmit
				else
				{
					//Find out Mail exchange server
					MXLookup mx = new MXLookup();
					
					try
					{
						List<String> mx_list = mx.getMX(domain);
					
						for(String list : mx_list)
						{
							DebugInfo.print(DEBUG, "Data class - Domain: "+ domain +" MX record: "+list);
							
							//Retransmit data by using SMTP client
							//"ocn.ne.jp" does not use mx
							SMTPClient client;
							if(mx_record_enabled && !domain.endsWith("ocn.ne.jp")) { client = new SMTPClient(list); }
							else { client = new SMTPClient(domain); }
							
							//Does not send any more.
							if(client.sendMessage(man.getMailFromAddress(), man.getReceptAddresses(), mail_data)) { break; }
						}
					}
					catch(Exception ex) 
					{
						DebugInfo.print(DEBUG, "Exception in retransmission.");
						
						pmp.changeState(new Transaction());
						
						//Error
						ArrayList<String> out_list = new ArrayList<String>();
						out_list.add("554 Transaction failed");
						
						return out_list;
					}
				}
			}
			
			//Clear all recp email addresses
			man.clearReceptAddresses();
			
			//Reply after "."
			ArrayList<String> out_list = new ArrayList<String>();
			out_list.add("250 ok");
			DebugInfo.print(DEBUG, "Data State: Replied");
			
			pmp.changeState(new Transaction());
			
			return out_list;
		}
		else 
		{
			DebugInfo.print(DEBUG, "Data State: null return");
			
			return null;
		}
	}
}